package com.example.sunran.utils;

import java.io.*;

public class FileUtils {
    private static final int TYPE_IMAGE = -1;
    private static final int TYPE_VIDEO = -2;
    private static final int TYPE_DOC = -3;
    private static final int TYPE_OTHER = -4;

    private static final String SAVE_PATH ="./UploadFile/";
    static {
        String[] folderName = new String[]{"Image","Video","Doc","Other"};
        for(String name:folderName){
            File file = new File(SAVE_PATH +name);
            if(!file.exists()){
                file.mkdirs();
            }
        }
    }
    public static void saveFile(String fileName, InputStream stream) throws IOException {
        int fileType = getFileType(fileName);
        File file = null;
        if(fileType==TYPE_IMAGE){
            file = new File(SAVE_PATH +"Image/"+fileName);
        }else if(fileType==TYPE_DOC){
            file = new File(SAVE_PATH +"Doc/"+fileName);
        }else if(fileType==TYPE_VIDEO){
            file = new File(SAVE_PATH +"Video/"+fileName);
        }else{
            file = new File(SAVE_PATH +"Other/"+fileName);
        }

        if (!file.exists()) {
            file.createNewFile();
        }
        byte[] bytes = new byte[1024];
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        int len = 0;
        while ((len=stream.read(bytes)) != -1) {
            fileOutputStream.write(bytes,0,len);
        }
        fileOutputStream.flush();
        fileOutputStream.close();
    }

    public static int getFileType(String fileName){

        if (fileName == null || fileName.equals("")) {
            return 0;
        }

        String prefix = fileName.substring(fileName.lastIndexOf(".")+1).toLowerCase();
        if(prefix.equals("bmp")||prefix.equals("jpg")||prefix.equals("jpeg")||prefix.equals("png")){
            return TYPE_IMAGE;
        }else if(prefix.equals("avi")||prefix.equals("mp4")||prefix.equals("rmvb")||prefix.equals("mkv")){
            return TYPE_VIDEO;
        }else if(prefix.equals("doc")||prefix.equals("ppt")||prefix.equals("txt")||prefix.equals("pdf")){
            return TYPE_DOC;
        }else{
            return TYPE_OTHER;
        }
    }
}
